package org.util;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Socket {
	private SocketConnection socket = null;
    private InputStream in = null;
    private OutputStream out = null;
    public Socket(String host, int port, int timeout) throws IOException{
    	
    	socket = (SocketConnection) Connector.open("socket://" + host + ":" + port);
    	// set application-specific options on the socket. Call setSocketOption to set other options
    	socket.setSocketOption(SocketConnection.DELAY, 0);
    	socket.setSocketOption(SocketConnection.KEEPALIVE, 0);    	                
    	socket.setSocketOption(SocketConnection.LINGER, 0);
    	this.setReadTimeout(timeout);
    	
        //socket = new Socket(secondServerIP, Integer.parseInt(secondServerPort), 25000);
    }
    public boolean isOpen() {
    	if (this.socket == null) return false;
    	else return true;
    }
    public void writeBytes(byte buf[], int start, int count) throws IOException {
        this.out = this.socket.openOutputStream();                
        this.out.write(buf, start, count);
    }
    
    public void writeBytes(byte buf[]) throws IOException {
        this.out = this.socket.openOutputStream();                
        this.out.write(buf, 0, buf.length);
    }
    public int readBytes(byte buf[]) throws IOException {    	    	
    	this.in = this.socket.openInputStream();
		return this.in.read(buf, 0, buf.length);
    	
    }
    public int readCheck() throws IOException {
    	this.in = this.socket.openInputStream();
		return this.in.available();  	
    }
    public void close() throws IOException{
    	this.in.close();
    	this.out.close();
    	this.socket.close();
    }
    public void flush() throws Exception {
    	this.out.flush();
    }
    public void setReadTimeout(int timeout){
    	int time;
    	time = timeout;
    }
}
